<template>
  <div class="p-2">
    <div class="viewBox">
      <div class="title-item">
        <span class="line-box"></span><span>{{ title }}</span>
      </div>
      <el-form ref="testTeachScheduleFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="testName">
          <!-- <el-input v-model="form.testName" placeholder="请输入名称" v-if="type != 2" /> -->
          <el-select v-model="form.testName" clearable placeholder="请选择名称"  v-if="type != 2" @change="testNameChange">
            <el-option v-for="dict in testOptions" :key="dict.id" :label="dict.testName" :value="dict.id"></el-option>
          </el-select>
          <div v-else> {{ getTestById(testOptions, form.testName) }}</div>
        </el-form-item>
        <el-form-item label="学科" prop="testSubject">
          <!-- <el-input v-model="form.testSubject" placeholder="请输入学科" /> -->
          <el-select v-model="form.testSubject" clearable placeholder="请选择学科" v-if="type != 2" :disabled="true">
            <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id" ></el-option>
          </el-select>
          <div v-else>{{ getSubjectNameById(subjectOptions, form.testSubject) }}</div>
        </el-form-item>
        <el-form-item label="年级" prop="testGrade">
          <!-- <el-input v-model="form.testGrade" placeholder="请输入年级" /> -->
          <el-select v-model="form.testGrade" placeholder="请选择年级" clearable v-if="type != 2" :disabled="true">
            <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <div v-else><dict-tag :options="sys_grade" :value="form.testGrade" /></div>
        </el-form-item>

        <el-form-item label="学年" prop="courseYear">
          <el-select v-model="form.courseYear" placeholder="请选择学年" clearable v-if="type != 2">
            <el-option v-for="dict in sys_stu_year" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else><dict-tag :options="sys_grade" :value="form.courseGrade" /></div>
        </el-form-item>
        <el-form-item label="学段" prop="testPeriod">
          <!-- <el-input v-model="form.testPeriod" placeholder="请输入学段" /> -->
          <el-select v-model="form.testPeriod" placeholder="请选择学段" clearable v-if="type != 2">
            <el-option v-for="dict in sys_period" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <div v-else><dict-tag :options="sys_period" :value="form.testPeriod" /></div>
        </el-form-item>
        <el-form-item label="学校" prop="deptId"  v-if="userId === 1 && tenantDisabled">
          <el-select v-model="form.deptId" placeholder="请选择学校" clearable @change="deptChange">
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="testClass">
          <!-- <el-input v-model="form.testClass" placeholder="请输入班级" v-if="type != 2" /> -->
          <el-select v-model="form.testClass" placeholder="请选择班级" clearable v-if="type != 2">
            <el-option v-for="dict in classOptions" :key="dict.id" :label="dict.className" :value="dict.id" />
          </el-select>
          <div v-else>{{ form.testClass }}</div>
        </el-form-item>
       
        
        <el-form-item label="授课老师" prop="testTeacher">
          <!-- <el-input v-model="form.testTeacher" placeholder="请输入授课老师" v-if="type != 2" /> -->
          <el-select v-model="form.testTeacher" placeholder="请选择授课老师" v-if="type != 2">
            <el-option v-for="dict in teacherList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
          <div v-else>{{ form.testTeacher }}</div>
        </el-form-item>
        <el-form-item label="授课教室" prop="testRoot">
          <!-- <el-input v-model="form.testRoot" placeholder="请输入授课教室" v-if="type != 2" />
          <div v-else>{{ form.testRoot }}</div> -->
          <el-select v-model="form.testRoot" placeholder="请选择授课教室" v-if="type != 2">
            <el-option v-for="dict in classRoomList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
          <!-- <div v-else>{{ form.testTeacher }}</div> :picker-options="pickerOptionsEnd"-->
        </el-form-item>
        <el-form-item label="授课时间" prop="testDate">
          <el-date-picker v-if="type != 2" clearable v-model="form.testDate"   type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss" 
            placeholder="年/月/日"
           :disabledDate = "disabledTestDateFun"
            @change="testDateChange">
          </el-date-picker>
          <div v-if="type != 2" style="margin: 0 5px;"> -</div>
          <el-date-picker
            v-if="type != 2"
            clearable
            v-model="form.testDateEnd"
             type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
           placeholder="年/月/日"
           :disabledDate = "disabledEndDateFun"
          >
          </el-date-picker>
          <!-- <div style="width:300px" v-if="type != 2">
            <el-date-picker  clearable v-model="dateArray"   type="datetimerange" range-separator=" - "
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="年/月/日" end-placeholder="年/月/日">
            </el-date-picker>
          </div> -->
         
          <div v-else>{{ form.testDate }} -{{form.testDateEnd}}</div>
        </el-form-item>
        <el-form-item label="开课二维码" prop="" v-if="type == 2">
          <img style="width:100px;height:100px" :src="imgUrl" alt="">
          <a style="color:#05AFEA;margin-left:20px" :href="downImgUrl">下载</a>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="type != 2">确 定</el-button>
        <el-button @click="edit" v-if="type != 0 && type != 1">编辑</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="handleDelete" v-if="type != 0 && type != 1">删除</el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="TestTeachSchedule" lang="ts">
import {
  listTestTeachSchedule,
  getTestTeachSchedule,
  delTestTeachSchedule,
  addTestTeachSchedule,
  updateTestTeachSchedule,
  qrCode
} from '@/api/core/testTeachSchedule';
import { TestTeachScheduleVO, TestTeachScheduleQuery, TestTeachScheduleForm } from '@/api/core/testTeachSchedule/types';
import { listDept } from '@/api/system/dept'; //学校
import { DeptVO } from '@/api/system/dept/types'; //学校
import { listTeacher} from '@/api/core/teacher';
import { listRoom } from '@/api/core/room';
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_notice_type, sys_period, sys_grade, sys_stu_year} = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period', 'sys_grade','sys_stu_year'));
const testTeachScheduleList = ref<TestTeachScheduleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const teacherList = ref([]);
const classRoomList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const testTeachScheduleFormRef = ref<ElFormInstance>();
// 共有数据方法
import { getSubjectNameById,getTestById } from '@/utils/index';
import { useSubjectList } from '@/composables/useSubjectList';
import { useClassList, useTenantlList } from '@/composables/useSchoolList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
const { classOptions, fetchClasslList} = useClassList();

import { useTeatList } from '@/composables/useSubjectList';
const { testOptions, fetchTestList } = useTeatList();

const imgUrl = ref<string>()
const downImgUrl = ref<string>()
const dateArray = ref<any>()
// const disabledDateFun = ref<any>()
const disabledTestDateFun = time =>{
  if(form.value.testDateEnd){
    const startTime = form.value.testDateEnd.substr(0,10) + ' 00:00:00';
    const endTime = form.value.testDateEnd.substr(0,10) +  ' 23:59:59';
    return time.getTime() < new Date(startTime).getTime() || time.getTime() > new Date(endTime).getTime()
  }
}
const disabledEndDateFun = time =>{
  if(form.value.testDate){
    const startTime = form.value.testDate.substr(0,10) + ' 00:00:00';
    const endTime = form.value.testDate.substr(0,10) +  ' 23:59:59';
    return time.getTime() < new Date(startTime).getTime() || time.getTime() > new Date(endTime).getTime()
  }
}
const testDateChange = (e) =>{
  console.log(e,'选择了开始时间',form.value.testDate,)
  if(form.value.testDate){
    const startTime = form.value.testDate.substr(0,10) + ' 00:00:00';
    const endTime = form.value.testDate.substr(0,10) +  ' 23:59:59';
    // disabledDateFun.value = time.getTime() < new Date(form.value.testDate).getTime() || time.getTime() > new Date(endTime).getTime()//确保开始时间和结束时间只能选择某一天的时分秒
  }
}
//  () => {
// 		disabledDate = (time) => {
// 		  if (this.ruleForm.startTime) {
//             const startTime = this.ruleForm.startTime.substr(0,10) + ' 00:00:00';
//             const endTime = this.ruleForm.startTime.substr(0,10) +  ' 23:59:59';
// 			return (
					
// 						)
// 					}
// 				},
// 			}
  //   }
  // }

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//动态字段
const title = ref('');
const formId = ref('');
const type = ref<string | number>();
// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]); //学校
//学校改租户数据
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

const initFormData: TestTeachScheduleForm = {
  testName: undefined,
  deptId:undefined,
  courseYear: undefined,
  testPeriod: undefined,
  testGrade: undefined,
  testClass: undefined,
  testSubject: undefined,
  testTeacher: undefined,
  testRoot: undefined,
  testDate: undefined,
  testDateEnd: undefined,

};
const data = reactive<PageData<TestTeachScheduleForm, TestTeachScheduleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId:undefined,
    testName: undefined,
    testPeriod: undefined,
    testGrade: undefined,
    testClass: undefined,
    testSubject: undefined,
    testTeacher: undefined,
    testRoot: undefined,
    testDate: undefined,
    testDateEnd: undefined,
    params: {}
  },
  rules: {
    testName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '学校不能为空', trigger: 'blur' }],
    testPeriod: [{ required: true, message: '学段不能为空', trigger: 'blur' }],
    testGrade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    testClass: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    testSubject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    testTeacher: [{ required: true, message: '授课老师不能为空', trigger: 'blur' }],
    testRoot: [{ required: true, message: '授课教室不能为空', trigger: 'blur' }],
    testDate: [{ required: true, message: '授课开始时间不能为空', trigger: 'blur' }],
    testDateEnd: [{ required: true, message: '授课结束时间不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询学校列表 */
const getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
};

const testNameChange = async (e) => {
  let list = toRaw(testOptions.value)
  list.forEach(ele =>{
    if(ele.id == e){
      //带出学科和年级数据
      form.value.testSubject = +ele.subject;
      form.value.testGrade = ele.grade;
    }
  })
  console.log('实验名称选择',e,toRaw(testOptions.value),form.value.testGrade,form.value.testSubject);
};
//学校选择
const deptChange = async (e) => {
  //根据学校id获取班级列表
  fetchClasslList(e)
  //根据学校获取授课老师
  queryParams.value.deptId = e;
  const response = await listTeacher(queryParams.value);
  teacherList.value = response.rows.map((item) => ({ id: item.id, name: item.name }));
  // 根据学校获取授课教室
  const classData = await listRoom({pageNum:1,pageSize:1000,schoolId:e});
  classRoomList.value = classData.rows.map((item) => ({ id: item.id, name: item.clsName }));
}

/** 取消按钮 */
const cancel = () => {
  reset();
  proxy?.$router.go(-1);
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  testTeachScheduleFormRef.value?.resetFields();
};

const edit = () => {
  type.value = '1';
  title.value = '编辑';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TestTeachScheduleVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTestTeachSchedule(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改教学实验排课';
};

/** 提交按钮 */
const submitForm = () => {
  testTeachScheduleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.deptId = tenantId;
      }
      // form.value.testDate = new Date(form.value.testDate).getTime();
      if (form.value.id) {
        await updateTestTeachSchedule(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('编辑成功');
      } else {
        await addTestTeachSchedule(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      proxy?.$router.go(-1);
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async () => {
  await proxy?.$modal.confirm('是否确认删除教学实验排课编号为"' + form.value.id + '"的数据项？').finally(() => (loading.value = false));
  await delTestTeachSchedule(form.value.id);
  proxy?.$modal.msgSuccess('删除成功');
  proxy?.$router.go(-1);
};

/** 获取数据 */
(async () => {
  formId.value = route.query && (route.query.id as string);
  type.value = route.query && (route.query.type as string);
  if (type.value == '0') {
    title.value = '新增';
  } else if (type.value == '1') {
    title.value = '编辑';
  } else {
    title.value = '查看';
    
  }
  if (formId.value) {
    const res = await getTestTeachSchedule(formId.value);
    res.data.testName = res.data?+res.data.testName:''
    res.data.testGrade = res.data?res.data.testGrade.toString():'';
    Object.assign(form.value, res.data);
    if(res.data){
      //获取开课二维码
      // const row = await qrCode({teacherId:res.data.testTeacher});
      imgUrl.value = 'http://47.119.113.53:60666/api/app/course/qrCode?teacherId='+res.data.testTeacher;
      downImgUrl.value = 'http://47.119.113.53:60666/api/app/course/qrCode?download= true&teacherId='+res.data.testTeacher;
      console.log('下载地址',imgUrl.value,downImgUrl.value);
    }
    
  }
  const response = await listTeacher(queryParams.value);
  teacherList.value = response.rows.map((item) => ({ id: item.id, name: item.name }));
  //授课教室数据
  const classData = await listRoom({pageNum:1,pageSize:1000});
  classRoomList.value = classData.rows.map((item) => ({ id: item.id, name: item.clsName }));

  fetchTestList()
  fetchSubjectList();
  getSchoolList();
})();
</script>

<style lang="scss" scoped>
.viewBox {
  margin: 15px 15px 80px 15px;
  .title-item {
    display: flex;
    align-items: center;
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    margin: 30px 0 20px;
    span {
      display: inline-block;
      margin: 0 5px;
    }
    .line-box {
      width: 4px;
      height: 24px;
      background: #05afea;
    }
  }
  .topTit {
    margin-top: 10px;
  }
  .el-form-item--default {
    margin: 15px 30px;
  }
  :deep(.el-textarea__inner) {
    width: 300px !important;
  }
  .el-input {
    width: 300px;
  }
  .el-select {
    width: 300px;
  }
  .dialog-footer {
    margin-top: 100px;
    text-align: center;
  }
}

.imgView-box {
  :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete) {
    display: none !important;
  }
  :deep(.el-upload--picture-card) {
    display: none !important;
  }

  :deep(.el-upload-list__item.is-success .el-upload-list__item-status-label),
  :deep(.el-icon--close-tip),
  :deep(.el-icon--close) {
    display: none !important;
  }
}
</style>
